package org.jeecg.modules.iot.common;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.iot.aio.Aio;
import org.jeecg.modules.iot.aio.AioConfiguration;
import org.jeecg.modules.iot.aio.ChannelContext;
import org.jeecg.modules.iot.aliyun.IotUtils;
import org.jeecg.modules.iot.util.IotClientUtil;
import org.jeecg.modules.power.device.entity.YlDevice;
import org.jeecg.modules.power.device.service.IYlDeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 初始化ChannelContext、AioConfiguration
 * 2、初始化一个 {@link IotConst.ID_ATOMIC}
 * @author scw
 * @version v1.0
 * @date
 */
@Component
@Slf4j
public class InitAioConfig implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private IYlDeviceService deviceService;
    @Autowired
    private IotClientUtil iotClientUtil;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {

        /**
         * 初始化ID最小值
         */
        QueryWrapper<YlDevice> queryWrapper = new QueryWrapper<>();
        queryWrapper.select(" max(device_qrcode_id) device_qrcode_id").last("limit 1");
        YlDevice device = deviceService.getOne(queryWrapper);
        if(oConvertUtils.isEmpty(device) || oConvertUtils.isEmpty(device.getDeviceQrcodeId()) ){
            IotConst.ID_ATOMIC = new AtomicInteger(10000);
        }else{
            String maxId = device.getDeviceQrcodeId().substring(0,5);
            IotConst.ID_ATOMIC = new AtomicInteger(Integer.valueOf(maxId));
        }

        /**
         * 初始化产品配置
         * 支出key以,形式隔开配置
         */
        String keys[] = iotClientUtil.getProductKey().split(",");
        for(String key:keys){
            AioConfiguration configuration = new AioConfiguration(key,iotClientUtil);
            Aio.setConfMap(key,configuration);
            /**
             * 直接开启一个线程查询MNS消息
             */
            configuration.queryMessageRunnable.execute();
        }

    }




}
